#include "led.h"
#include "delay.h"

void BSP_LED_SetState(volatile Device_LED *dv, State_LED state){
    dv->state = state;
    GPIO_TypeDef *GPIO_Port = dv->GPIO_Port;
    uint16_t GPIO_Pin = dv->GPIO_Pin;
    if(dv->bitValWhenStateIsOn == Bit_RESET){
        if(state==LED_ON){
            GPIO_WriteBit(GPIO_Port, GPIO_Pin, Bit_RESET);
        }else{
            GPIO_WriteBit(GPIO_Port, GPIO_Pin, Bit_SET);
        }
    }else{
        if(state==LED_ON){
            
            GPIO_WriteBit(GPIO_Port, GPIO_Pin, Bit_SET);
        }else{
            GPIO_WriteBit(GPIO_Port, GPIO_Pin, Bit_RESET);
        }
    }
}

void BSP_LED_ToggleState(volatile Device_LED *dv){
    if(dv->state == LED_ON){
        BSP_LED_SetState(dv, LED_OFF);
    }else{
        BSP_LED_SetState(dv, LED_ON);
    }
}

void BSP_LED_Flash(volatile Device_LED *dv, uint32_t periodDurUs, uint32_t nPeriods, uint8_t isInIrq){
    void (*delayCmd)(uint32_t);
    int i;
    if(isInIrq){
        delayCmd = BSP_DelayUsInIrq;
    }else{
        delayCmd = BSP_DelayUs;
    }
    
    BSP_LED_SetState(dv, LED_OFF);
    
    for(i = 0; i < nPeriods; i++){
        BSP_LED_ToggleState(dv);
        delayCmd(periodDurUs/2);
        BSP_LED_ToggleState(dv);
        delayCmd(periodDurUs/2);
    }
    
    return;
}

State_LED BSP_LED_SyncState(volatile Device_LED *dv){
    GPIO_TypeDef *GPIO_Port = dv->GPIO_Port;
    uint16_t GPIO_Pin = dv->GPIO_Pin;
    
    uint8_t bitVal = GPIO_ReadOutputDataBit(GPIO_Port, GPIO_Pin);
    if(dv->bitValWhenStateIsOn == (uint8_t)RESET){
        if(bitVal == (uint8_t)RESET){
            dv->state = LED_ON;
        }else{
            dv->state = LED_OFF;
        }
    }else{
        if(bitVal == (uint8_t)RESET){
            dv->state = LED_OFF;
        }else{
            dv->state = LED_ON;
        }
    }
    return dv->state;
}
